//
//  Passcode.m
//  Pocket Doctor alpha version
//
//  Created by Sherif, Yin, Taylor, Jacob, Anna, Mike on 11-10-25.
//  Copyright (c) 2011 __Sytjam__. All rights reserved.
//
//Class Description: Ask for Passcode before launching medicine view or calendar.
//                   Recovering passcode can be achieved from here as well. (forget passcode)
//
//Known Bugs: none.
//

#import "Passcode.h"
#import "MainMenu.h"
#import "MedicineView.h"
#import "AddMedicine.h"

#import "Kal/src/Kal.h"
#import "ReminderDataSource.h"

NSString *userQuestion, *userHint, *userPasscode, *userAnswer;

@implementation Passcode

@synthesize hint, go, passcode, forgotPasscode, secretQuestion, secretAnswer, cancel, done, back, passcodeContain, secretAnswerContain;
@synthesize mm, mv, aD, kal;
@synthesize editID, medicineOrCalendar;


/*Cancel On passcode*/
- (IBAction)Back:(id)sender{
    
    [passcode resignFirstResponder];
    [secretAnswer resignFirstResponder];
    
    /*MainMenu *mmObject = [[MainMenu alloc]initWithNibName:@"MainMenu" bundle:nil];
    self.mm = mmObject;
    [mmObject release];
    
    mm.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:mm animated:YES];*/
    
    [self dismissModalViewControllerAnimated:YES];
}

/*In case the user forgets their passcode
 they can access the secret question and 
 answer
 Hides passcode
 reveals secret Q&A*/
- (IBAction)Forgot:(id)sender{
    [passcode resignFirstResponder];
    [secretAnswer resignFirstResponder];
    passcode.text = @"";
    
    hint.hidden = true;
    go.hidden   = true;
    passcode.hidden = true;
    forgotPasscode.hidden = true;
    
    secretQuestion.hidden = false;
    secretAnswer.hidden = false;
    cancel.hidden = false;
    done.hidden = false; 
    
}

/*cancel secret q&a to go back to write the passcode*/
- (IBAction)Cancel:(id)sender{
    [passcode resignFirstResponder];
    [secretAnswer resignFirstResponder];
    
    secretAnswer.text = @"";
    
    hint.hidden = false;
    go.hidden   = false;
    passcode.hidden = false;
    forgotPasscode.hidden = false;
    
    secretQuestion.hidden = true;
    secretAnswer.hidden = true;
    cancel.hidden = true;
    done.hidden = true; 
}

/*Check if the secret answer matches
 if it matches then the passcode is shown in an alert*/
- (IBAction)CheckSecretAnswer:(id)sender{
    [passcode resignFirstResponder];
    [secretAnswer resignFirstResponder];
    NSString *currentAnswer = [[NSString alloc]initWithFormat:[secretAnswer.text lowercaseString]];
    if([currentAnswer isEqualToString:userAnswer]){
        //nav proceed.
        secretAnswer.text = @"";
        NSString *message = [[NSString alloc]initWithFormat:@"Your Passcode is : %@", userPasscode];
        UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:@"Reminder" message:message delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
        
        [alert1 show];
        [alert1 release];
        [message release];

        hint.hidden = false;
        go.hidden   = false;
        passcode.hidden = false;
        forgotPasscode.hidden = false;
        
        secretQuestion.hidden = true;
        secretAnswer.hidden = true;
        cancel.hidden = true;
        done.hidden = true; 
    }
    else{
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error!" message:@"Incorrect Answer" delegate:nil cancelButtonTitle:@"Ok!" otherButtonTitles: nil];
        
        [alert show];
        [alert release];
    }
}

/*Checks the written passcode
 then if its right; the medicine view
 is accessed*/
- (IBAction)Check:(id)sender{
    [passcode resignFirstResponder];
    [secretAnswer resignFirstResponder];
    NSString *currentPasscode = [[NSString alloc]initWithFormat:passcode.text];
    if([currentPasscode isEqualToString:userPasscode]){
        
        if (medicineOrCalendar==0) {
            MedicineView *mvObject = [[MedicineView alloc]initWithNibName:@"MedicineView" bundle:nil];
            self.mv = mvObject;
            [mvObject release];
            
            mv.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
            [self presentModalViewController:mv animated:YES];
        }else{ 
            if (medicineOrCalendar==1) {
                id<KalDataSource> source = [[ReminderDataSource alloc] init];
                KalViewController *kalObject = [[[KalViewController alloc] init] autorelease];
                kalObject.dataSource = source;
                self.kal = kalObject;
                [kalObject release];
                kal.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                [self presentModalViewController:kal animated:YES];
            }
        }
        
    }
    else{
        passcode.text = @"";
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error!" message:@"Incorrect Passcode" delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
        
        [alert show];
        [alert release];
    }
}

//Support Functions
/*tap background to get rid of keyboard*/
- (IBAction)tapBackground:(id)sender{
    [passcode resignFirstResponder];
    [secretAnswer resignFirstResponder];
}

/*done on keyboard will get rid of the keyboard*/
- (IBAction)tapDoneKeyboard:(id)sender{
    [sender resignFirstResponder];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        editID = -1; // Set the initial value of editID.
    }
    return self;
}

/*Animate View upwards to prevent keyboard covering the textfields*/
- (IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}


- (IBAction)textFieldDidEndEditing:(UITextField *)textField
{
    [self animateTextField: textField up: NO];
}

- (void) animateTextField: (UITextField *) textField up: (BOOL) up
{
    const int movementDistance = 80; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed
    
    int movement = (up ? -movementDistance : movementDistance);
    
    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}
//end animation

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*Load userpasscode; hint; secret question and answer*/
- (void)viewDidLoad
{
    //Load User preferences (Security) from database.
    
    aD = [[UIApplication sharedApplication] delegate];
    
    sqlite3_stmt * statement;
    NSString * enforceForeignKey = @"PRAGMA foreign_keys = 1";
    const char * query_stmt = [enforceForeignKey UTF8String];
    
    NSString *loadSecurity = [[NSString alloc]initWithFormat:@"SELECT passcode, passcode_hint, secret_question, secret_answer FROM security;"];    
    query_stmt = [loadSecurity UTF8String];
    if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
        
        if (sqlite3_step(statement) == SQLITE_ROW){
            //[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
            // Row Exists for security. advance to main menu
            NSString *userPasscodeObject = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
            NSString *userHintObject = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
            NSString *userQuestionObject = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
            NSString *userAnswerObject = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)];
            
            userPasscode = userPasscodeObject;
            userHint = userHintObject;
            userQuestion = userQuestionObject;
            userAnswer = userAnswerObject;
            
            //without assigning these strings to outlets, their values are lost. todo: why?
            
            hint.text = userHint;
            secretQuestion.text = userQuestion;
            passcodeContain.text = userPasscode;
            secretAnswerContain.text = userAnswer;
        }

    }

    
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void) dealloc{
    
    [mm release];
    [mv release];
    [aD release];
    [kal release];
    
    [hint release];
    [go release];
    [passcode release];
    [forgotPasscode release];
    [secretQuestion release];
    [secretAnswer release];
    [cancel release];
    [done release];
    [back release];
    [passcodeContain release];
    [secretAnswerContain release];
    
    [super dealloc];
}

@end
